import React, { useState, useEffect } from 'react';
import { useDispatch } from 'umi';
import { TreeSelect } from 'antd';
import './OrgTreeSelect.css'

function updateTreeData(list, key, children) {
  return list.map((node) => {
    if (node.value === key) {
      return { ...node, children };
    }
    if (node.children) {
      return { ...node, children: updateTreeData(node.children, key, children) };
    }
    return node;
  });
}

const OrgTreeSelect = (props) => {
  const [treeData, setTreeData] = useState([]);
  const dispatch = useDispatch();
  const { isOpencustomizedSelectAll, customizedSelectAll, ...otherProps } = props;
  useEffect(() => {
    const getRootTree = () => {
      dispatch({
        type: 'common/getOrgRootTree',
      }).then((data) => {
        setTreeData(data);
      });
    };
    getRootTree();
  }, []);

  const onLoadData = (data) => {
    const { key, children } = data;
    return new Promise((resolve) => {
      if (children) {
        resolve();
        return;
      }
      dispatch({
        type: 'common/getChildOrgListByParentId',
        payload: {
          parentId: parseInt(key),
        },
      }).then((childData) => {
        if (childData && childData.length > 0) {
          const newList = updateTreeData(treeData, parseInt(key), childData);
          setTreeData(newList);
          resolve();
        }
      });
    });
  };
  const { TreeNode } = TreeSelect;
  const renderTreeNodes = data => data.map((item) => {
    if (isOpencustomizedSelectAll) {
      if (item.children) {
        return (
          <TreeNode {...item} key={item.value} dataRef={item} 
            title={<span><span className='spanLeftVisible'>{item.title}</span><span onClick={(e) => {e.stopPropagation();customizedSelectAll(item.children)}} className='spanRightHide' style={{color:'red',fontSize:'0.5rem'}}>&ensp;&ensp;全选</span></span>}
          >
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
    } else {
      if (item.children) {
        return (
          <TreeNode {...item} key={item.value} dataRef={item}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
    }
    return <TreeNode {...item} key={item.value} dataRef={item} />;
  })
  return (
    <TreeSelect
      loadData={onLoadData}
      // treeData={treeData}
      {...otherProps}
    >
      {renderTreeNodes(treeData)}
    </TreeSelect>
  );
};

export default OrgTreeSelect;
